let currentRoleId = null;

// 打开菜单分配对话框
function openMenuAssign(roleId) {
    currentRoleId = roleId;
    $('#menuTreeContainer').empty();
    $('#menuAssignModal').show();

    $.ajax({
        url: '/sysMenu/getAllMenu',
        method: 'GET',
        success: function(res) {
            const menus = res.data || [];
            const tree = buildMenuTree(menus);
            renderMenuTree(tree, $('#menuTreeContainer'));
        }
    });
}

// 构建菜单树
function buildMenuTree(menus) {
    const map = {};
    const tree = [];

    menus.forEach(menu => {
        map[menu.menuId] = menu;
        menu.children = [];
    });

    menus.forEach(menu => {
        if (menu.parentId && map[menu.parentId]) {
            map[menu.parentId].children.push(menu);
        } else if (!menu.parentId) {
            tree.push(menu);
        }
    });

    return tree.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
}

// 渲染菜单树
function renderMenuTree(tree, container, level = 0) {
    const indent = '　'.repeat(level * 2); // 中文缩进

    tree.forEach(menu => {
        const html = `
            <div style="margin-left:${level * 20}px">
                <label>
                    <input type="checkbox" data-menu-id="${menu.menuId}"> 
                    ${indent}${menu.menuName}
                </label>
            </div>`;
        container.append(html);

        if (menu.children && menu.children.length > 0) {
            renderMenuTree(menu.children, container, level + 1);
        }
    });
}

// 获取已选菜单 ID 并保存
function saveAssignedMenus() {
    const selectedMenuIds = $('#menuTreeContainer input[type=checkbox]:checked').map(function () {
        return $(this).data('menu-id');
    }).get();

    // 这里可以调用保存接口，例如：
    $.ajax({
        url: '/role/assignMenu',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            roleId: currentRoleId,
            menuIds: selectedMenuIds
        }),
        success: function () {
            alert("菜单分配成功");
            $('#menuAssignModal').hide();
        },
        error: function () {
            alert("分配失败，请重试");
        }
    });
}